import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/home/index.vue'
import PostDetailView from '../views/post-detail/index.vue'
import PublishView from '../views/publish/index.vue'
import AboutView from '../views/about/index.vue'
import NotFoundView from '../views/not-found/index.vue'
import LoginView from '../views/login/index.vue'
import RegisterView from '../views/register/index.vue'
import UserProfileView from '../views/user-profile/index.vue'

const routes = [
  { path: '/', component: HomeView },
  { path: '/blog', redirect: '/' }, // 重定向到首页
  { path: '/post/:id', component: PostDetailView }, // 改为 /post/:id
  { path: '/publish', component: PublishView },
  { path: '/about', component: AboutView },
  { path: '/login', component: LoginView },
  { path: '/register', component: RegisterView },
  { path: '/profile', component: UserProfileView },
  {
    path: '/edit/:id',
    name: 'EditArticle',
    component: () => import('../views/edit-article/index.vue'),
    meta: { requiresAuth: true }
  },
  { path: '/:pathMatch(.*)*', component: NotFoundView }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && to.path !== '/register' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
